package com.example.spidertp.business.service.impl;

import com.example.spidertp.business.service.SimulateExportService;
import com.example.spidertp.core.SpiderThreadPool;
import com.example.spidertp.core.SpiderThreadPoolFactory;
import com.example.spidertp.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author xiong.bo
 * @version 1.0
 * @date 2022/9/18 11:29 上午
 */

@Slf4j
@Service
public class SimulateExportServiceImpl implements SimulateExportService {


    /**
     * 模拟把多个任务放到线程池中去执行
     * @return
     */
    @Override
    public boolean exportUserData() {
        log.info("exportUserData start");

        SpiderThreadPool threadPool = SpiderThreadPoolFactory.getThreadPool("user");
        if(threadPool == null){
            throw new BusinessException("该线程池对象为空！");
        }

        for (int i = 0; i < 100; i++) {
            log.info("exportUserData task" + i);
            Runnable runnable = () -> {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info("do something");
            };
            threadPool.execute(runnable);
        }
        log.info("exportUserData end");
        return true;
    }

    @Override
    public boolean exportOrderData() {
        log.info("exportUserData start");

        SpiderThreadPool threadPool = SpiderThreadPoolFactory.getThreadPool("order");
        if(threadPool == null){
            throw new BusinessException("该线程池对象为空！");
        }

        for (int i = 0; i < 100; i++) {
            log.info("exportOrderData task" + i);
            int finalI = i;
            Runnable runnable = () -> {
                try {
                    if(finalI == 30 || finalI == 40){
                        //测试超时任务
                        Thread.sleep(6000);
                    }else{
                        Thread.sleep(1000);
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info("do something");
            };
            threadPool.execute(runnable);
        }
        log.info("exportOrderData end");
        return true;
    }
}
